<!-- 库存 -->
<template>
  <div class="main-content-container">
    <div ref="search" class="app-search">
      <el-row>
        <el-col :span="12" class="searchInput">
          <el-form ref="searchFormRef" :inline="true">
            <el-form-item>
              <el-input v-model="custQuery" class="inputCss" placeholder="请输入名称或拼音码" clearable @change="handleChange">
                <el-button slot="append" icon="el-icon-search" @click="handleChange" />
              </el-input>
            </el-form-item>
            <!-- <el-form-item>
              <el-button type="primary" @click="handleChange">搜索</el-button>
              <el-button @click="eliminate">清除</el-button>
            </el-form-item> -->
          </el-form>
        </el-col>
        <el-col :span="12" align="right" class="addBtnStyle">
          <el-button type="primary" @click="stockButton">+ 入库</el-button>
          <el-button type="primary" @click="writeOffButton">+ 冲减</el-button>
          <el-button type="primary" @click="inventoryButton">+ 盘点</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" :clearable="true" class="el-select-y" @change="warehouseChange">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-row>
    </div>
    <!-- 表单区域  -->
    <div class="box-show marginTop" :style="'height:'+ (innerHeight + 80) + 'px'">
      <el-table v-loading="loading" :data="inventoryList" border :row-class-name="tableColor" :height="innerHeight">
        <el-table-column label="编号" prop="materialMedicineNo" :show-overflow-tooltip="true" />
        <el-table-column label="名称" prop="inventoryName" :show-overflow-tooltip="true" />
        <el-table-column label="拼音码" prop="materialMedicineSearchCode" :show-overflow-tooltip="true" />
        <el-table-column label="生成厂商" prop="inventoryProducer" :show-overflow-tooltip="true" />
        <el-table-column label="类型" prop="inventoryType" :show-overflow-tooltip="true" />
        <el-table-column label="规格" prop="inventorySpecl" :show-overflow-tooltip="true" />
        <el-table-column label="单位" prop="inventoryUnit" :show-overflow-tooltip="true" />
        <el-table-column label="售价" prop="materialMedicineSellPrice" :show-overflow-tooltip="true" />
        <el-table-column label="仓库" prop="warehouseName" :show-overflow-tooltip="true" />
        <el-table-column label="当前库存" prop="stockCount" :show-overflow-tooltip="true" />
        <el-table-column label="可用库存" prop="availableStock" :show-overflow-tooltip="true" />
        <el-table-column label="操作" min-width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="addOrReduceRecord(scope.row)">库存记录</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :page-num="params.page" :page-size="params.pageSize" :on-change="handlePaginationChange" :total="total" />
    </div>
    <!-- 冲减 -->
    <RecordDialog v-if="visible" :visible.sync="visible" :inventory-data="inventoryData" @handleClose="handleClose" />
    <WarehousingDialog v-if="stockVisible" :visible.sync="stockVisible" @handleClose="handleClose" @successHandle="submitStockForm" />
    <WriteDownDialog v-if="writeOffVisible" :visible.sync="writeOffVisible" @handleClose="handleClose" @successHandle="writeDownHnadle" />
    <InventoryDialog v-if="inventoryVisible" :visible.sync="inventoryVisible" @handleClose="handleClose" @successHandle="successHandle" />
  </div>
</template>
<script>
import { selections } from "@/config";
import { warehouseList } from "@/utils/common";
import { tableColor, labelHeigh } from '@/utils/common.js';
import RecordDialog from "./recordDialog";
import WarehousingDialog from "./warehousingDialog";
import WriteDownDialog from "./writeDownDialog";
import InventoryDialog from "./InventoryDialog";
window.onbeforeunload = event => {
  window.scrollTo(0, 0); // 每次刷新，滚动条在页面最上面
};
export default {
  components: {
    RecordDialog,
    WarehousingDialog,
    WriteDownDialog,
    InventoryDialog,
  },
  data() {
    return {
      selections,
      searchForm: {},
      options: [],
      custQuery: "",
      categorys: [
        {
          id: "药品",
          name: "药品",
        },
        {
          id: "物品",
          name: "物品",
        },
      ],
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      total: 0,
      paramsTwo: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      totalTwo: 0,
      inventoryList: [],
      inventoryData: {},
      optionsos: [],
      inventoryTableData: [],
      formInline: {},
      warehouseList: [],
      requestInfo: {
        discount: 0,
        medicalAdvice: '',
      },
      searchParams: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      stockInfo: {},
      addGoodsList: [],
      goodsList: [],
      tableColor,
      innerHeight: null,
      title: "",
      visible: false,
      inventoryVisible: false,
      loading: false,
      stockVisible: false,
      stockLoading: false,
      searchLoading: false,
      goodsVisible: false,
      goodsLoading: false,
      writeOffInfo: {},
      writeOffVisible: false,
      writeOffLoading: false,
      pickerOptions: {
        disabledDate(time) { // 禁用选择之后的日期
          return time.getTime() > Date.now() - 8.64e7;
        },
      },
    };
  },
  mounted() {
    this.getInventoryList();
    this.findAllWarehouse();
    this.innerHeight = labelHeigh(this.$refs.search);
  },
  methods: {
    async getInventoryList() {
      this.loading = true;
      const res = await this.$api['warehouse/inventory/inventoryList']({ ...this.params, query: this.searchForm, custQuery: this.custQuery });
      this.loading = false;
      if (res.code !== 200) return this.$message.error('查询库存列表失败！');
      this.inventoryList = res.data.result;
      this.total = res.data.total;
    },
    handlePaginationChange(val) {
      this.params = { page: val.pageNum, pageSize: val.pageSize };
      this.getInventoryList();
    },
    async warehouseChange(val) {
      if (val) {
        this.searchForm.warehouseId = val;
      } else {
        this.searchForm.warehouseId = undefined;
      }
      this.getInventoryList();
    },
    // 库存记录
    addOrReduceRecord(row) {
      this.inventoryData = row;
      this.visible = true;
    },
    // 获取库房列表
    async findAllWarehouse() {
      this.warehouseList = warehouseList();
    },
    // 关闭
    handleClose() {
      this.inventoryData = {};
      this.visible = false;
      this.stockVisible = false;
      this.writeOffVisible = false;
      this.inventoryVisible = false;
      // this.$refs.requestFromRef.resetFields();
    },
    // 入库
    stockButton() {
      this.stockVisible = true;
    },
    // 冲减
    writeOffButton() {
      this.writeOffVisible = true;
    },
    // 盘点
    inventoryButton() {
      this.inventoryVisible = true;
    },
    // 获取产品分类id
    async getClassificationId(val) {
      // 查询提交的产品分类id
      this.searchParams.productClassificationId = val.list.join(",");
      this.searchParams.inventory = "进货";
      const res = await this.$api['warehouse/stock/goodsList']({ query: this.searchParams });
      if (res.code !== 200) return this.$message.error('查询货品列表失败！');
      this.addGoodsList = res.data;
      if (this.goodsList.length > 0) {
        this.$nextTick(function() {
          this.addGoodsList.forEach(item => {
            this.goodsList.forEach(json => {
              if (item.id === json.id) {
                this.$refs.stockTable.toggleRowSelection(item, true);
                this.$refs.writeOffTable.toggleRowSelection(item, true);
              }
            });
          });
        });
      }
    },
    // 搜索商品
    async searchGoods() {
      this.searchLoading = true;
      const res = await this.$api['warehouse/stock/goodsList']({ query: this.searchParams });
      console.log(res.data);
      this.searchLoading = false;
      if (res.code !== 200) return this.$message.error('查询货品列表失败！');
      this.addGoodsList = res.data;
    },
    // 选择商品
    selectionChange(a, val) {
      let isExistence = false;
      this.goodsList.forEach((item, index) => {
        if (item.id === val.id) {
          isExistence = true;
          this.goodsList.splice(index, 1);
        }
      });
      if (!isExistence) {
        const json = JSON.parse(JSON.stringify(val));
        this.goodsList.push(json);
      }
      this.goodsList.filter(item => {
        item.materialMedicineId = item.id;
        item.inventoryProducer = item.producerName;
      });
      console.log(this.goodsList);
    },
    handleSelectAll(selection) {
      if (selection.length > 0) {
        selection.forEach(item => {
          let isExistence = false;
          this.goodsList.forEach(json => {
            if (json.id === item.id) {
              isExistence = true;
            }
          });
          if (!isExistence) {
            this.goodsList.push(item);
          }
        });
      } else {
        this.addGoodsList.forEach(item => {
          this.goodsList.forEach((json, index) => {
            if (json.id === item.id) {
              this.goodsList.splice(index, 1);
              index--;
            }
          });
        });
      }
    },
    // 提交进货表单
    async submitStockForm() {
      this.stockVisible = false;
      this.getInventoryList();
    },
    // 关闭
    handleCloseStock() {
      this.searchLoading = false;
      this.stockLoading = false;
      // this.$refs.ruleForm.resetFields();
    },
    // 选择商品
    async writeOffChange(a, val) {
      const pamars = {
        materialMedicineId: val.id,
      };
      let isExistence = false;
      this.goodsList.forEach((item, index) => {
        if (item.id === val.id) {
          isExistence = true;
          this.goodsList.splice(index, 1);
        }
      });
      if (!isExistence) {
        this.goodsLoading = true;
        const res = await this.$api['warehouse/writeOff/findInventory']({ query: pamars });
        this.goodsLoading = false;
        if (res.code !== 200) return this.$message.error('查询商品列表失败！');
        if (res.data.length === 0) {
          this.addGoodsList.forEach(item => {
            if (val.id === item.id) {
              this.$refs.writeOffTable.toggleRowSelection(item, false);
            }
          });
          return this.$message.error('所选商品暂无库存！');
        }
        res.data.filter(item => {
          item.name = item.inventoryName;
          item.specs = item.inventorySpecl;
          item.batchId = item.inventoryBatch;
          item.dueDate = item.inventoryExpiredDate;
          item.supplier = item.inventorySupplier;
          item.unit = item.inventoryUnit;
          item.inventoryId = item.id;
        });
        val.detail = res.data;
        const json = JSON.parse(JSON.stringify(val));
        this.goodsList.push(json);
      }
    },
    // 提交冲减表单
    async submitWriteOffForm() {
      console.log("提交冲减表单");
      // 添加仓库名称
      this.goodsList.forEach((goods, index) => {
        this.goodsList[index].detail.forEach(detail => {
          this.warehouseList.forEach(warehouse => {
            if (detail.warehouseId === warehouse.id) {
              detail.warehouseName = warehouse.name;
            }
          });
        });
      });
      const listDto = [];
      let check = false;
      this.goodsList.forEach((goods, index) => {
        this.goodsList[index].detail.forEach(detail => {
          listDto.push(detail);
        });
      });
      listDto.forEach(item => {
        if (!item.writeOffCount) check = true;
      });
      if (check) return this.$message.error('冲减数量不能为空！');
      if (listDto.length === 0) return this.$message.error('冲减商品不能为空！');
      this.writeOffLoading = true;
      const res = await this.$api['warehouse/writeOff/writeOff']({ listDto: listDto, ...this.writeOffInfo });
      this.writeOffLoading = false;
      this.writeOffVisible = false;
      this.goodsList = [];
      if (res.code !== 200) return this.$message.error('添加冲减失败！');
      this.$message.success('添加冲减成功！');
      this.getInventoryList();
    },
    handleCloseWriteOff() {
      this.searchLoading = false;
      this.writeOffLoading = false;
    },
    async deleteDetailBtn(index, row) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      for (var i = 0; i < this.goodsList[index].detail.length; i++) {
        if (this.goodsList[index].detail[i].id === row.id) {
          this.goodsList[index].detail.splice(i, 1);
          if (this.goodsList[index].detail.length === 0) {
            this.goodsList.splice(index, 1);
          }
        }
      }
      this.$message.success('删除商品成功！');
    },
    handleChange() {
      this.params.page = 1;
      this.getInventoryList();
    },
    eliminate() {
      this.searchForm = {};
      this.custQuery = "";
      this.params.page = 1;
      this.getInventoryList();
    },
    successHandle() {
      this.inventoryVisible = false;
      this.getInventoryList();
    },
    writeDownHnadle() {
      this.writeOffVisible = false;
      this.getInventoryList();
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
